﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Thread = System.Threading.Tasks;
using Microsoft.Practices.Unity;
using Infrastucture;
using Infrastucture.Collections;
using TimeSplicerModule.Factories;
using TimeSplicerModule.DomainModels;
using TimeSplicerModule.Security;
using TimeSplicerModule.ViewModels;
using TimeSplicerModule.Services;

namespace TimeSplicerModule.Services
{
    public partial class TaskService : ITaskService
    {
        public TaskListViewModel GetTaskListViewModel()
        {
            _session = _container.Resolve<ISession>();

            var model = new TaskListViewModel();
            model.Tasks = new List<TaskModel>();

            var statuses = _session.Statuses; //_statusFactory.GetList();

            model.Users = _userService.GetViewableUsers(); // can probably put this in the container as well
            model.Statuses = statuses.Where(x => x.IsTaskStatus && x.IsActive).OrderBy(o => o.SortOrder).ToList();  //_statusFactory.GetList(x => x.IsTaskStatus && x.IsActive);


            //var tasks = _taskFactory.GetList();

            //tasks.AsParallel().ForAll(x => x.Status = statuses.FirstOrDefault(s => s.StatusGuid == x.StatusGuid));
            

            // limit tasks to viewable user tasks


            var me = model.Users.FirstOrDefault(x => x.UserGuid == _session.User.UserGuid);
            var projects = _projectService.GetList(me);
            var myTasks = _taskFactory.GetList(x => x.AssignedToGuid == me.UserGuid);
            myTasks.AsParallel().ForAll(x => 
                {
                    x.Status = statuses.FirstOrDefault(s => s.StatusGuid == x.StatusGuid);
                    x.Project = projects.FirstOrDefault(p => p.ProjectGuid == x.ProjectGuid);
                });

            model.Tasks.AddRange(myTasks);

            //foreach (var u in model.Users)
            //{
            //    var userTasks = tasks.Where(x => x.AssignedToGuid == u.UserGuid).ToList();

            //    if (userTasks.Count > 0)
            //    {
            //        foreach (var ut in userTasks)
            //        {
            //            ut.Project = _projectService.Get(ut.ProjectGuid);

            //            var stamps = _timestampService.GetList(ut);

            //            ut.Hours = GetTaskHours(stamps);
            //        }

            //        model.Tasks.AddRange(userTasks);
            //    }
            //}

            // then need to filter on user
            model.SelectedUserGuid = _session.User.UserGuid;
            model.FilteredTasks = model.Tasks.Where(x => x.AssignedToGuid == model.SelectedUserGuid).ToObservableCollection();
           // model.FilteredTasks = model.FilteredTasks.OrderBy(O => O.ActualHours).ToObservableCollection();


            return model;
        }
    }
}
